/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar.lualib;

import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.ZeroArgFunction;

import com.google.gson.JsonObject;
import com.lucky_byte.pay.jar.JdbcRecord;

public class LuaJdbcRecord extends ZeroArgFunction
{
	private final JdbcRecord record;

	public LuaJdbcRecord(JdbcRecord record) {
		this.record = record;
	}

	@Override
	public LuaValue call() {
		LuaValue library = tableOf();
		library.set("_object", LuaValue.userdataOf(record));

		library.set("get", new getField());
		library.set("set", new setField());
		library.set("tojson", new toJson());
		return library;
	}

	/**
	 * 取记录中的字段
	 */
	class getField extends OneArgFunction
	{
		@Override
		public LuaValue call(LuaValue arg0) {
			Object object = record.getField(arg0.checkjstring());
			if (object == null) {
				return LuaValue.NIL;
			}
			return LuaHelper.object2Value(object);
		}
	}

	/**
	 * 设置字段的值
	 */
	class setField extends TwoArgFunction
	{
		@Override
		public LuaValue call(LuaValue arg1, LuaValue arg2) {
			String key = arg1.checkjstring();
			record.setField(key, LuaHelper.value2Object(arg2));
			return arg2;
		}
	}

	/**
	 * 转换为 JSON 字符串
	 */
	class toJson extends ZeroArgFunction
	{
		@Override
		public LuaValue call() {
			JsonObject json = record.toJson();
			return LuaValue.valueOf(json.toString());
		}
	}
}
